/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.rest.front;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import me.zhengjie.annotation.AnonymousAccess;
import me.zhengjie.annotation.Log;
import me.zhengjie.modules.system.bo.req.*;
import me.zhengjie.modules.system.bo.resp.QztySetUpIndexResp;
import me.zhengjie.modules.system.domain.*;
import me.zhengjie.modules.system.service.*;
import me.zhengjie.modules.system.service.dto.*;
import me.zhengjie.modules.system.util.IPUtils;
import me.zhengjie.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
* @website https://eladmin.vip
* @author cjl
* @date 2023-05-16
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "DCC我的设置相关管理")
@RequestMapping("/front/setup")
public class FrontMyController {




    private final DccFankuiService dccFankuiService;


    private final DccJifenService dccJifenService;
    private final DccDakaService dccDakaService;
    private final DccQunzhongtianyanService dccQunzhongtianyanService;
    private final DccUserService dccUserService;
    private final DccDizhiService dccDizhiService;
    private final DccXiaoxiService dccXiaoxiService;
    private final DccCollectService dccCollectService;


    private final   EntityManager entityManager;


//    @Log("我的收藏")
//    @ApiOperation("我的收藏")
//    @AnonymousAccess
//    @PostMapping(value = "/mycollect")
//    public ResponseEntity<Map<String, Object>> mycollect(@RequestBody QueryBaseReq baseReq){
//        DccCollectQueryCriteria dccCollectQueryCriteria=new DccCollectQueryCriteria();
//        Sort sort =Sort.by(Sort.Direction.DESC,"updatedAt");
//        dccCollectQueryCriteria.setUid(StpUtil.getLoginIdAsString());
//        Pageable pageable =PageRequest.of(baseReq.getPage()-1, baseReq.getSize(),sort);
//        Map<String, Object> stringObjectMap = dccCollectService.queryAllInner(dccCollectQueryCriteria, pageable);
//        return new ResponseEntity<>(stringObjectMap,HttpStatus.OK);
//
//    }





    @Log("设置首页")
    @ApiOperation("设置首页,目前只返回头像和简介")
    @AnonymousAccess
    @PostMapping(value = "/index")
    public ResponseEntity<QztySetUpIndexResp> index(){
        if (!StpUtil.isLogin()){
            return new ResponseEntity<>(null,HttpStatus.UNAUTHORIZED);
        }
        QztySetUpIndexResp qztySetUpIndexResp =new QztySetUpIndexResp();
        DccUserDto user = (DccUserDto) StpUtil.getSession().get("user");
        qztySetUpIndexResp.setName(user.getNickName());
        qztySetUpIndexResp.setHeadImg(user.getAvatar());
        qztySetUpIndexResp.setQianming(user.getQianming());

        return new ResponseEntity<>(qztySetUpIndexResp,HttpStatus.OK);
    }


    @Log("问题反馈")
    @ApiOperation("问题反馈")
    @AnonymousAccess
    @PostMapping(value = "/fankui")
    public ResponseEntity<Object> index(@RequestBody DccFankuiReq yplyReq){
        if (!StpUtil.isLogin()){
            return new ResponseEntity<>(null,HttpStatus.UNAUTHORIZED);
        }

        DccFankui dccFankui=new DccFankui();
        BeanUtil.copyProperties(yplyReq,dccFankui);
        dccFankui.setStatus(0);
        dccFankui.setCreatedAt(new Timestamp(System.currentTimeMillis()));
        dccFankui.setUpdatedAt(new Timestamp(System.currentTimeMillis()));
        dccFankuiService.create(dccFankui);
        return new ResponseEntity<>("反馈成功",HttpStatus.OK);

    }


    @Log("打卡")
    @ApiOperation("打卡")
    @AnonymousAccess
    @PostMapping(value = "/daka")
    public ResponseEntity<Object> daka(HttpServletRequest request){
        if (!StpUtil.isLogin()){
            return new ResponseEntity<>(null,HttpStatus.UNAUTHORIZED);
        }

        DccDaka dccDaka=new DccDaka();
        DccDakaQueryCriteria dccDakaQueryCriteria=new DccDakaQueryCriteria();
        String format = DateUtil.format(new Date(), "yyyy-MM-dd");
        dccDaka.setRiqi(format);
        dccDaka.setStatus(1);
        dccDaka.setPoint(10);
        Integer dday=1;
        dccDakaQueryCriteria.setRiqi(format);
        dccDakaQueryCriteria.setUid(StpUtil.getLoginIdAsString());
        List<DccDakaDto> dccDakaDtos = dccDakaService.queryAll(dccDakaQueryCriteria);
        if (!CollectionUtils.isEmpty(dccDakaDtos)){
            dday=dccDakaDtos.get(0).getType()+1;
        }
        dccDaka.setType(dday);
        dccDaka.setUid(StpUtil.getLoginIdAsString());
        dccDaka.setOperator(IPUtils.getRemortIP(request));
        dccDaka.setCreatedAt(new Timestamp(System.currentTimeMillis()));
        dccDaka.setUpdatedAt(new Timestamp(System.currentTimeMillis()));
        DccDakaDto dccDakaDto = dccDakaService.create(dccDaka);
        //查询昨天是否有打卡 有就判断昨天的text是几，让后加一
        //积分上传记录
        DccJifen dccJifen=new DccJifen();
        dccJifen.setUid(StpUtil.getLoginIdAsString());
        dccJifen.setPoint(10);
        dccJifen.setCommonId(dccDakaDto.getId());
        dccJifen.setText("打卡积分,连续打卡第"+dday+"天");
        dccJifen.setType(1);
        dccJifen.setStatus(1);
        dccJifen.setCreatedAt(new Timestamp(System.currentTimeMillis()));
        dccJifen.setUpdatedAt(new Timestamp(System.currentTimeMillis()));
        dccJifenService.create(dccJifen);
        DccUserDto user = (DccUserDto) StpUtil.getSession().get("user");
        int i = Integer.parseInt(StringUtils.isEmpty(user.getGroupid())?"0":user.getGroupid()) + 10;
        user.setGroupid(i+"");
        StpUtil.getSession().set("user",user);
        DccUser dccUser=new DccUser();
        BeanUtil.copyProperties(user,dccUser);
        dccUser.setUpdatedAt(new Timestamp(System.currentTimeMillis()));
        dccUserService.update(dccUser);
        return new ResponseEntity<>(dday,HttpStatus.OK);
    }

    @Log("我的举报")
    @ApiOperation("我的举报")
    @AnonymousAccess
    @PostMapping(value = "/jubao")
    public ResponseEntity<Map<String, Object>> jubao(@RequestBody QueryBaseReq baseReq){
        if (!StpUtil.isLogin()){
            return new ResponseEntity<>(null,HttpStatus.UNAUTHORIZED);
        }

        DccQunzhongtianyanQueryCriteria criteria =new DccQunzhongtianyanQueryCriteria();
        criteria.setOperator(StpUtil.getLoginIdAsString());
        Sort sort =Sort.by(Sort.Direction.DESC,"updatedAt");
        Pageable pageable =PageRequest.of(baseReq.getPage()-1, baseReq.getSize(),sort);
        Map<String, Object> stringObjectMap = dccQunzhongtianyanService.queryAll(criteria, pageable);
        return new ResponseEntity<>(stringObjectMap,HttpStatus.OK);
    }




    @Log("地址新增")
    @ApiOperation("地址新增")
    @AnonymousAccess
    @PostMapping(value = "/dizhiadd")
    public ResponseEntity<Object> dizhiadd(@RequestBody DizhiReq yplyReq){
        if (!StpUtil.isLogin()){
            return new ResponseEntity<>(null,HttpStatus.UNAUTHORIZED);
        }

        DccDizhi resources =new DccDizhi();
        resources.setUid(StpUtil.getLoginIdAsString());
        BeanUtil.copyProperties(yplyReq,resources);
        if (yplyReq.getStatus()!=null&&yplyReq.getStatus().equals(new Integer(1))){
            resources.setStatus(1);
        }else {
            resources.setStatus(0);
        }
        resources.setCreatedAt(new Timestamp(System.currentTimeMillis()));
        resources.setUpdatedAt(new Timestamp(System.currentTimeMillis()));
        dccDizhiService.create(resources);
        return new ResponseEntity<>("地址新增成功",HttpStatus.OK);

    }


    @Log("地址修改")
    @ApiOperation("地址修改")
    @AnonymousAccess
    @PostMapping(value = "/dizhiupdate")
    public ResponseEntity<Object> dizhiupdate(@RequestBody DizhiUpdateReq yplyReq){
        if (!StpUtil.isLogin()){
            return new ResponseEntity<>(null,HttpStatus.UNAUTHORIZED);
        }

        DccDizhiDto dccDizhiServiceById = dccDizhiService.findById(yplyReq.getId());
        dccDizhiServiceById.setStatus(yplyReq.getStatus());
        dccDizhiServiceById.setUpdatedAt(new Timestamp(System.currentTimeMillis()));
        DccDizhi dizhm=new DccDizhi();
        BeanUtil.copyProperties(dccDizhiServiceById,dizhm);
        dccDizhiService.update(dizhm);
        DccDizhiQueryCriteria dccDizhiQueryCriteria=new DccDizhiQueryCriteria();
        dccDizhiQueryCriteria.setUid(StpUtil.getLoginIdAsString());
        List<DccDizhiDto> dccDizhiDtos = dccDizhiService.queryAll(dccDizhiQueryCriteria);
        dccDizhiDtos.stream().forEach(
                e->{
                    if (!e.getId().equals(yplyReq.getId())){
                        e.setStatus(0);
                        DccDizhi dizhi=new DccDizhi();
                        BeanUtil.copyProperties(e,dizhi);
                        dizhi.setUpdatedAt(new Timestamp(System.currentTimeMillis()));
                        dccDizhiService.update(dizhi);
                    }
                }
        );


        return new ResponseEntity<>("地址修改成功",HttpStatus.OK);

    }




    @Log("我的地址")
    @ApiOperation("我的地址")
    @AnonymousAccess
    @PostMapping(value = "/dizhi")
    public ResponseEntity<Object> dizhi(@RequestBody QueryBaseReq queryBaseReq){
        if (!StpUtil.isLogin()){
            return new ResponseEntity<>(null,HttpStatus.UNAUTHORIZED);
        }

        DccDizhiQueryCriteria criteria =new DccDizhiQueryCriteria();
        criteria.setUid(StpUtil.getLoginIdAsString());
        Sort sort =Sort.by(Sort.Direction.DESC,"updatedAt");
        Pageable pageable =PageRequest.of(queryBaseReq.getPage()-1, queryBaseReq.getSize(),sort);
        Map<String, Object> stringObjectMap = dccDizhiService.queryAll(criteria, pageable);
        return new ResponseEntity<>(stringObjectMap,HttpStatus.OK);
    }



    @Log("消息中心")
    @ApiOperation("消息中心")
    @AnonymousAccess
    @PostMapping(value = "/xiaoxi")
    public ResponseEntity<Object> xiaoxi(@RequestBody QueryBaseReq queryBaseReq){
        if (!StpUtil.isLogin()){
            return new ResponseEntity<>(null,HttpStatus.UNAUTHORIZED);
        }

        DccXiaoxiQueryCriteria criteria =new DccXiaoxiQueryCriteria();
        criteria.setUid(StpUtil.getLoginIdAsString());
        Sort sort =Sort.by(Sort.Direction.DESC,"updatedAt");
        Pageable pageable =PageRequest.of(queryBaseReq.getPage()-1, queryBaseReq.getSize(),sort);
        Map<String, Object> stringObjectMap = dccXiaoxiService.queryAll(criteria, pageable);
        return new ResponseEntity<>(stringObjectMap,HttpStatus.OK);
    }


    @Log("全部读取消息")
    @ApiOperation("全部读取消息")
    @AnonymousAccess
    @PostMapping(value = "/duqu")
    public ResponseEntity<Object> duqu(@RequestBody QztyXiaoxiReq queryBaseReq){
        if (!StpUtil.isLogin()){
            return new ResponseEntity<>(null,HttpStatus.UNAUTHORIZED);
        }

        DccXiaoxiQueryCriteria criteria =new DccXiaoxiQueryCriteria();
        if (queryBaseReq.getType().equals("all")){
            criteria.setUid(StpUtil.getLoginIdAsString());
            List<DccXiaoxiDto> dccXiaoxiDtos = dccXiaoxiService.queryAll(criteria);
            dccXiaoxiDtos.forEach(e->{
                e.setStatus(1);
                DccXiaoxi dccXiaoxi=new DccXiaoxi();
                BeanUtil.copyProperties(e,dccXiaoxi);
                dccXiaoxiService.update(dccXiaoxi);
            });
        }else  if (queryBaseReq.getType().equals("id")){
            DccXiaoxiDto byId = dccXiaoxiService.findById(queryBaseReq.getId());
            byId.setStatus(1);
            DccXiaoxi dccXiaoxi=new DccXiaoxi();
            BeanUtil.copyProperties(byId,dccXiaoxi);
            dccXiaoxiService.update(dccXiaoxi);
        }else{
            return new ResponseEntity<>("数据类型异常",HttpStatus.OK);
        }
        return new ResponseEntity<>(HttpStatus.OK);
    }




    @Log("我的积分")
    @ApiOperation("我的积分")
    @AnonymousAccess
    @PostMapping(value = "/jifen")
    public ResponseEntity<Object> jifen(@RequestBody QueryBaseReq queryBaseReq){
        if (!StpUtil.isLogin()){
            return new ResponseEntity<>(null,HttpStatus.UNAUTHORIZED);
        }

        DccJifenQueryCriteria criteria =new DccJifenQueryCriteria();
        criteria.setUid(StpUtil.getLoginIdAsString());
        Sort sort =Sort.by(Sort.Direction.DESC,"updatedAt");
        Pageable pageable =PageRequest.of(queryBaseReq.getPage()-1, queryBaseReq.getSize(),sort);
        Map<String, Object> stringObjectMap = dccJifenService.queryAllFront(criteria, pageable);
        DccUserDto user = (DccUserDto) StpUtil.getSession().get("user");
        stringObjectMap.put("totalJifen", StringUtils.isEmpty(user.getGroupid())?"0":user.getGroupid());
        return new ResponseEntity<>(stringObjectMap,HttpStatus.OK);
    }








}